package app.Disthanitian.thaistyle.EmerMez;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.provider.BaseColumns._ID;
import static app.Disthanitian.thaistyle.EmerMez.Constant.NAME;
import static app.Disthanitian.thaistyle.EmerMez.Constant.ORIGINLAT;
import static app.Disthanitian.thaistyle.EmerMez.Constant.ORIGINLNG;
import static app.Disthanitian.thaistyle.EmerMez.Constant.DESTINATIONLAT;
import static app.Disthanitian.thaistyle.EmerMez.Constant.DESTINATIONLNG;
import static app.Disthanitian.thaistyle.EmerMez.Constant.TIMES;
import static app.Disthanitian.thaistyle.EmerMez.Constant.TYPE;
import static app.Disthanitian.thaistyle.EmerMez.Constant.TABLE_NAME;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import android.R.color;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment.SavedState;
import android.app.ProgressDialog;
import android.app.ActionBar.OnNavigationListener;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory.Options;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	GoogleMap mMap;
	GoogleMapOptions option;	
	OutputStream output;	
	PolylineOptions rectLine;	
	PolygonOptions rectGon;
	ProgressDialog mProgressDialog;
	String urls = "";
	Document docs;	
	Thread background;
	DatabaseConnection db;
	FileOutputStream fos;
	Document doc;
	ProgressDialog dialog;
	SQLiteDatabase mdb;
	
	ArrayList<RiskZone> riskArea;	
	Cursor mCursor;
	Intent i;
	RiskZone risk,risk1;
	int count=0;
	double x1,x2,y1,y2;	
	String addresName,addresName1,addresName2;	
	Marker x,y;
	Address bestMatch;
	Button myButton;
	
	//From PHP
	RiskZoneAll riskAll;
	//ArrayList<LatLng> directionPoints[];
	
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		
		setContentView(R.layout.activity_main);
		mMap = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map)).getMap();
		mMap.setMyLocationEnabled(true);
		//getOverflowMenu();
		//searcAddress();
		//moveToCurrentPosition();
		
		actionBar();
		
		
		// Get RiskZone
		db = new DatabaseConnection(MainActivity.this);
		risk1 = new RiskZone();
		riskAll = new RiskZoneAll();
		risk = new RiskZone();
		riskArea = new ArrayList<RiskZone>();
		
		//riskArea = risk.getAllRiskZone(this);
		riskAll.setVariable(new MemberUser().getId(),"T");
		riskAll.callRun();
		while(riskAll.getRiskFromDB()==null){
			
		}
		//riskArea = riskAll.getAllRiskZone();
		
		riskArea = riskAll.getRiskFromDB();
		Log.d("ArraySize",""+riskAll.getRiskFromDB().size());
		//setOnCreateAttribute();
		/*if(isInRiskZone()){
			Toast.makeText(MainActivity.this,"In RiskZone",3).show();
		}*/
		// Download File and Save File
		//setLink();	
		
		//Set Button
		//setAllButton();	
		
		//Check Intent
		checkIntent();
		getDirectionPointArray();
		//LatLng x = new LatLng(13.745791500490375,100.53669936954975); //Out Risk Zone
		//LatLng x = new LatLng(13.745576881450372,100.53769614547491);	//In Risk Zone
		//LatLng x = new LatLng(13.754526230806714,100.54355844855309);	//Out Risk Zone
		//LatLng x = new LatLng(13.6871765,100.5352698);	//In Risk Zone
		LatLng x = new LatLng(13.748951165021,100.540897361);
		
		/*if(isInRiskZone(getDirectionPointArray(),x)){
			mMap.addMarker(new MarkerOptions().position(x));
			mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
					(x), 30));
			Toast.makeText(MainActivity.this,"In RiskZone",3).show();
		}else{
		Toast.makeText(MainActivity.this,"Passed",3).show();
		mMap.addMarker(new MarkerOptions().position(x).title(""+x.latitude+","+x.longitude));
		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
				(x), 15));
		}*/
		//showAllRiskZone();
		//moveToCurrentPosition();
		calculateDistance();

		mMap.setOnMapClickListener(new OnMapClickListener() {
			
			@Override
			public void onMapClick(LatLng arg0) {
				// TODO Auto-generated method stub
				
				mMap.addMarker(new MarkerOptions().title(""+arg0.latitude+":"+arg0.longitude).position(arg0));
				if(isInRiskZone(getDirectionPointArray(),arg0)){
				Toast.makeText(MainActivity.this,"In RiskZone",3).show();
			}else{
				Toast.makeText(MainActivity.this,"Out of RiskZone",3).show();
			}
			}
		});

		
	}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();		
		inflater.inflate(R.menu.main, menu);
		SearchView searchView = (SearchView)menu.findItem(R.id.action_main).getActionView();		
	    searchView.setOnQueryTextListener(queryListener);
	    return true;		
	}

	private class DownloadFile extends AsyncTask<String, Integer, String> {
		String path;

		public String getPath() {
			return path;
		}

		public void setPath(String path) {
			this.path = path;
		}

		@Override
		protected String doInBackground(String... sUrl) {
			try {
				URL url = new URL(sUrl[0]);
				URLConnection connection = url.openConnection();
				connection.connect();

				// this will be useful so that you can show a typical 0-100%
				// progress bar
				int fileLength = connection.getContentLength();

				// download the file
				InputStream input = new BufferedInputStream(url.openStream());
				for (RiskZone r : riskArea) {
					output = new FileOutputStream(path);					
				}
				byte data[] = new byte[1024];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int) (total * 100 / fileLength));
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();

			} catch (Exception e) {
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			/*
			 * mProgressDialog.setIndeterminate(false);
			 * mProgressDialog.setMax(100);
			 * mProgressDialog.setProgressStyle(ProgressDialog
			 * .STYLE_HORIZONTAL); mProgressDialog.show();
			 */

			// dialog = new ProgressDialog(context);
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			/*mProgressDialog.setProgress(progress[0]);
			if (mProgressDialog.getProgress() == 100)
				mProgressDialog.cancel();*/
		}

		

		private void destroyRunningThreads() {
			if (background != null) {
				background.interrupt();
				background = null;
				// background.stop();
			}
		}

	}
	
	public void setLink() {
		for (RiskZone r : riskArea) {

			urls = "http://maps.googleapis.com/maps/api/directions/xml?origin="
					+ r.getOiriginLat() + "," + r.getOriginLng()
					+ "&destination=" + r.getDestinationLat() + ","
					+ r.getDestinationLng()
					+ "&sensor=false&units=metric&mode=walking";
			DownloadFile downloadFile = new DownloadFile();
			downloadFile.setPath("/sdcard/EmerMez/riskZone/local/"
					+ r.getId() + ".xml");
			
			downloadFile.execute(urls);
		}

	}
	
	private void setOneLink(RiskZone r){
		urls = "http://maps.googleapis.com/maps/api/directions/xml?origin="
				+ x1 + "," + x2
				+ "&destination=" + y1 + ","
				+ y2
				+ "&sensor=false&units=metric&mode=walking";
		DownloadFile downloadFile = new DownloadFile();
		downloadFile.setPath("/sdcard/EmerMez/riskZone/local/"
				+ r.getId() + ".xml");
		downloadFile.execute(urls);
	}

	private void openInsertDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("Location: "+addresName);
		dialog.setItems(R.array.AddRiskZoneDialog,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(which==0){
							
							/*db = new DatabaseConnection(MainActivity.this);
							mdb = db.getWritableDatabase();
							String sql = "INSERT INTO "
									+ TABLE_NAME+ " ("+ NAME+ ", "+ ORIGINLAT+ ", "+ ORIGINLNG
									+ ", "+ DESTINATIONLAT+ ", "+ DESTINATIONLNG+ ", "+ TYPE
									+ ", "+ TIMES+ ") VALUES ('"+addresName+"','"+x1+"','"+x2+"','"+y1+"','"+y2+"','C',15);";
							mdb.execSQL(sql);
							db.close();								
							
							risk1= risk1.searchByPosition(MainActivity.this, x1, x2, y1, y2);	
							showOneRiskZoneById(risk1);*/
							RiskZone rrr = new RiskZone();
							rrr.setUserId(new MemberUser().getId());
							rrr.setNameStart(addresName1);
							rrr.setNameEnd(addresName2);
							rrr.setOiriginLat(""+x1);
							rrr.setOriginLng(""+x2);
							rrr.setDestinationLat(""+y1);
							rrr.setDestinationLng(""+y2);
							rrr.setType("L");
							Date currentTime = new Date();
							final SimpleDateFormat formatDate =
					                new SimpleDateFormat("yyyy-MM-dd");
					         final SimpleDateFormat formatTime =
					                new SimpleDateFormat("HH:mm:ss");             
					         rrr.setTime(formatTime.format(currentTime).toString());
					         rrr.setDate(formatDate.format(currentTime).toString());
							Log.d("Name1",""+rrr.getNameStart());
					        /*RiskZoneOption rr = new RiskZoneOption(rrr, new MemberUser().getId());					        
					        rr.setRateValue("5");
					        rr.setEnable("T");
					        rr.setTime_rate(formatTime.format(currentTime).toString());
					        rr.setDate_rate(formatDate.format(currentTime).toString());*/
					        
					        AddRiskZone add = new AddRiskZone();
							add.setVariable(rrr);
							add.callRun();
							/*AddRiskZoneLocalOption adds = new AddRiskZoneLocalOption();
							adds.setVariable(rr);
							adds.callRun();*/
							
							
						}else{
							removePins(x,y);
							x1=0;
							x2=0;
							y1=0;
							y2=0;
						}
						

					}
				});
		dialog.show();
	}

	/*private void setAllButton() {
		// Set Buttons View
		Button buttonNormal = (Button) findViewById(R.id.goMap);
		buttonNormal.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				openMapOptionDialog();
			}
		});

		Button buttonSatellite = (Button) findViewById(R.id.button2);
		buttonSatellite.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
			}
		});

		Button buttonTerrain = (Button) findViewById(R.id.button3);
		buttonTerrain.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
			}
		});

		Button buttonHybrid = (Button) findViewById(R.id.button4);
		buttonHybrid.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
			}
		});

		Button buttonLocate = (Button) findViewById(R.id.button7);
		buttonLocate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Criteria criteria = new Criteria();
				LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				String provider = locationManager.getBestProvider(criteria,
						false);
				Location location = locationManager
						.getLastKnownLocation(provider);
				double lat = location.getLatitude();
				double lng = location.getLongitude();
				LatLng coordinate = new LatLng(lat, lng);

				mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						(coordinate), 15));
				mMap.addMarker(new MarkerOptions()
						.position(coordinate)
						.title("Prove")
						.snippet("Family")
						.draggable(true)
						.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));	
			}
		})

		Button buttonInsert = (Button) findViewById(R.id.button6);		
		buttonInsert.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub			
				
				mMap.setOnMapLongClickListener(new OnMapLongClickListener() {
					
					@Override
					public void onMapLongClick(LatLng position) {							
						count+=1;
						Address bestMatch=null;
						if(count==2){
						y1 = position.latitude;
						y2 = position.longitude;						
						try {
							addresName2 = getRoadName(y1,y2);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							addresName2="";
						}
												
						y = mMap.addMarker( new MarkerOptions().position(position).title(
								"End").snippet(addresName2));						
						
						if(addresName1.equals(addresName2)){
							addresName = addresName2;
						}else{
							addresName = addresName1+addresName2;
						}						
						openInsertDialog();						
						count=0;
						Log.d("Database", "Passing");						
						addresName1 =null;
						addresName2 =null;
						
						}else{
							
							x1 = position.latitude;
							x2 = position.longitude;		
							
							Geocoder geoCoder = new Geocoder(MainActivity.this);
							List<Address> matches;
							try {
								matches = geoCoder.getFromLocation(x1, x2, 1);
								bestMatch = (matches.isEmpty() ? null : matches.get(0));
								addresName1 = bestMatch.getThoroughfare();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							
							x = mMap.addMarker(new MarkerOptions().position(position).title(
									"Start").snippet(addresName1));
							Toast.makeText(MainActivity.this, "Marks another(End) pin", 3).show();
						}
					}
				});
				Toast.makeText(MainActivity.this, "Pin on the map to mark the Risk Zone", 3).show();

			}
		});
		Button list = (Button) findViewById(R.id.button8);
		i = new Intent(this, ListRiskZoneActivity.class);
		list.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				openListOfRiskZoneOptions();

			}
		});

		Button buttonShowRisk = (Button) findViewById(R.id.button5);
		buttonShowRisk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				db = new DatabaseConnection(MainActivity.this);
				mdb = db.getWritableDatabase();
				String sql = "INSERT INTO "
						+ TABLE_NAME+ " ("+ NAME+ ", "+ ORIGINLAT+ ", "+ ORIGINLNG
						+ ", "+ DESTINATIONLAT+ ", "+ DESTINATIONLNG+ ", "+ TYPE
						+ ", "+ TIMES+ ") VALUES ('"+addresName+"','"+x1+"','"+x2+"','"+y1+"','"+y2+"','C',15);";
				
				mdb.execSQL(sql);
				db.close();
				riskArea = risk.getAllRiskZone(MainActivity.this);				
				setLink();
				showAllRiskZone();
			}
		});
		
		
	}*/

	public void showAllRiskZone(){
		String check = "OK";
		setLink();
		DocumentDirection dd = new DocumentDirection();	
		
		for (RiskZone r : riskArea) {
			
			docs = dd.getDocument("/sdcard/EmerMez/riskZone/local/"
					+ r.getId() + ".xml");	
			
			
			String status = dd.getStatus(docs);
			if(!status.equals(check)){
				continue;
			}else{
			int duration = dd.getDurationValue(docs);
			String distance = dd.getDistanceText(docs);
			String start_address = dd.getStartAddress(docs);
			String copy_right = dd.getCopyRights(docs);
			}
			
			mMap.addMarker(new MarkerOptions()
					.position(
							new LatLng(Double.parseDouble(r
									.getOiriginLat()), Double
									.parseDouble(r.getOriginLng())))
					.title("Start").snippet(r.getNameStart()));
			mMap.addMarker(new MarkerOptions()
					.position(
							new LatLng(Double.parseDouble(r
									.getDestinationLat()), Double
									.parseDouble(r.getDestinationLng())))
					.title("End").snippet(r.getNameEnd()));
			ArrayList<LatLng> directionPoint = dd.getDirection(docs);
		
			PolylineOptions rectLine = new PolylineOptions().width(3)
					.color(Color.RED);
			PolygonOptions rectGon = new PolygonOptions();
			rectGon.strokeColor(Color.BLACK).fillColor(Color.YELLOW).strokeWidth(3);
			double gonPointLat,gonPointLng;
			
			
			if(isVertical(directionPoint)){
			directionPoint = addMorePointInToDirectionPoint(directionPoint);
				
			for (int i = 0; i < directionPoint.size(); i++) {
				rectLine.add(directionPoint.get(i));
				//mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude,directionPoint.get(i).longitude)));
				/*mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude+0.00010,directionPoint.get(i).longitude+0.00010)));
				mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude-0.00010,directionPoint.get(i).longitude-0.00010)));
				mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude+0.00010,directionPoint.get(i).longitude-0.00010)));
				mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude-0.00010,directionPoint.get(i).longitude+0.00010)));*/
				gonPointLat= directionPoint.get(i).latitude;
				gonPointLng = directionPoint.get(i).longitude+0.00005;	
				
				rectGon.add((new LatLng(gonPointLat,gonPointLng)));
			}
			for (int i = directionPoint.size()-1; i > 0 ; i--) {				
				gonPointLat= directionPoint.get(i).latitude;
				gonPointLng = directionPoint.get(i).longitude-0.00005;				
				rectGon.add((new LatLng(gonPointLat,gonPointLng)));
			}
			}else{
				directionPoint = addMorePointInToDirectionPoint(directionPoint);
				for (int i = 0; i < directionPoint.size(); i++) {
					rectLine.add(directionPoint.get(i));
					//mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude,directionPoint.get(i).longitude)));
					/*mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude+0.00010,directionPoint.get(i).longitude+0.00010)));
					mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude-0.00010,directionPoint.get(i).longitude-0.00010)));
					mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude+0.00010,directionPoint.get(i).longitude-0.00010)));
					mMap.addMarker(new MarkerOptions().position(new LatLng( directionPoint.get(i).latitude-0.00010,directionPoint.get(i).longitude+0.00010)));*/
					gonPointLat= directionPoint.get(i).latitude+0.00005;
					gonPointLng = directionPoint.get(i).longitude;				
					rectGon.add((new LatLng(gonPointLat,gonPointLng)));
				}
				for (int i = directionPoint.size()-1; i > 0 ; i--) {				
					gonPointLat= directionPoint.get(i).latitude-0.00005;
					gonPointLng = directionPoint.get(i).longitude;				
					rectGon.add((new LatLng(gonPointLat,gonPointLng)));
				}
			}
			
			mMap.addPolyline(rectLine);
			mMap.addPolygon(rectGon);
			//moveToCurrentPosition();
		}
	}
		
	public boolean showOneRiskZoneById(RiskZone r){
		setOneLink(r);
		String check = "OK";
		DocumentDirection ddx = new DocumentDirection();
		Document docs1;	
			docs1 = ddx.getDocument("/sdcard/EmerMez/riskZone/local/"
					+ r.getId() + ".xml");	
			String status = ddx.getStatus(docs1);
			if(!status.equals(check)){
				return false;
			}else{
				int duration = ddx.getDurationValue(docs1);
				String distance = ddx.getDistanceText(docs1);
				String start_address = ddx.getStartAddress(docs1);
				String copy_right = ddx.getCopyRights(docs1);
				mMap.addMarker(new MarkerOptions().position(
							new LatLng(Double.parseDouble(r
									.getOiriginLat()), Double
									.parseDouble(r.getOriginLng())))
									.title("Start").snippet(r.getNameStart()));
				mMap.addMarker(new MarkerOptions()
						.position(
							new LatLng(Double.parseDouble(r
									.getDestinationLat()), Double
									.parseDouble(r.getDestinationLng())))
					.title("End").snippet(r.getNameEnd()));
			ArrayList<LatLng> directionPoint = ddx.getDirection(docs1);
			directionPoint = addMorePointInToDirectionPoint(directionPoint);
			PolylineOptions rectLine = new PolylineOptions().width(10)
					.color(Color.RED);
			
			PolygonOptions rectGon = new PolygonOptions();
			rectGon.strokeColor(Color.BLACK).fillColor(Color.YELLOW).strokeWidth(3);
			double gonPointLat,gonPointLng;
			
			if(isVertical(directionPoint)){
			for (int i = 0; i < directionPoint.size(); i++) {
				rectLine.add(directionPoint.get(i));
				
				gonPointLat= directionPoint.get(i).latitude;
				gonPointLng = directionPoint.get(i).longitude+0.00005;				
				rectGon.add((new LatLng(gonPointLat,gonPointLng)));
			}
			for (int i = directionPoint.size()-1; i > 0 ; i--) {				
				gonPointLat= directionPoint.get(i).latitude;
				gonPointLng = directionPoint.get(i).longitude-0.00005;				
				rectGon.add((new LatLng(gonPointLat,gonPointLng)));
			}
			}else{
				for (int i = 0; i < directionPoint.size(); i++) {
					rectLine.add(directionPoint.get(i));
					
					gonPointLat= directionPoint.get(i).latitude+0.00005;
					gonPointLng = directionPoint.get(i).longitude;				
					rectGon.add((new LatLng(gonPointLat,gonPointLng)));
				}
				for (int i = directionPoint.size()-1; i > 0 ; i--) {				
					gonPointLat= directionPoint.get(i).latitude-0.00005;
					gonPointLng = directionPoint.get(i).longitude;				
					rectGon.add((new LatLng(gonPointLat,gonPointLng)));
				}
			}
			
			mMap.addPolyline(rectLine);
			mMap.addPolygon(rectGon);
		}
			return true;
	
	}
			
	public void removePins(Marker x1,Marker x2){		
		x1.remove();
		x2.remove();
		
	}
	
	public void checkIntent(){
		Intent intent = getIntent();
		String extra= intent.getStringExtra("RiskZoneId");
		RiskZone risk1 = new RiskZone();
		if(extra!=null){			
			riskAll = new RiskZoneAll();
			//riskAll.setVariable(new MemberUser().getId());
			riskAll.callRun();
			while(riskAll.getRiskFromDB()==null){
				
			}
			riskArea = riskAll.getRiskFromDB();		
			for(RiskZone r : riskArea){
				if(r.getId().equals(extra)){
					risk1 = r;
					break;
				}else{
					continue;
				}
			}
				
		//risk1 = risk1.searchById(MainActivity.this, extra);	
		
		if(risk1!=null){
			//showOneRiskZoneById(risk1);
			LatLng posi = new LatLng(Double.parseDouble(risk1.getOiriginLat()),Double.parseDouble(risk1.getOriginLng()));
			showOneRiskZoneById(risk1);
			mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
					(posi), 15));	
			
			//Log.d("RRRRRRRR",""+posi.latitude);
		}
	}
	}	
	
	private void openMapOptionDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("Layers");
		dialog.setItems(R.array.MapOptionMenu,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which){
							case 0: mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
									Toast.makeText(MainActivity.this, "Normal Mode", 3).show();
									break;
							case 1: mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
									Toast.makeText(MainActivity.this, "Satellite Mode", 3).show();
									break;
							case 2: mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
									Toast.makeText(MainActivity.this, "Terrain Mode", 3).show();
									break;
							case 3: mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);	
								Toast.makeText(MainActivity.this, "Hybrid Mode", 3).show();
									break;
						}

					}
				});
		dialog.show();
	}
	
	public void turnOffLongClickMap(){
		mMap.setOnMapLongClickListener(null);
		Toast.makeText(MainActivity.this, "Cancle Adding Mode", 3).show();
	}
	
	private void openListOfRiskZoneOptions() {
		//final Intent i3 = new Intent(MainActivity.this,ListRiskZoneMyCentralActivity.class);
		//final Intent i3 = new Intent(MainActivity.this,ListRiskZoneMyLocalActivity.class);
		
		final Intent i1 = new Intent(MainActivity.this,ListRiskZoneAllCentralActivity.class);
		final Intent i2 = new Intent(MainActivity.this,ListRiskZoneAllLocalActivity.class);
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("Type of RiskZone");
		dialog.setItems(R.array.TypeOfRiskZone,
				new DialogInterface.OnClickListener() {

			
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which){
							case 0: 
							AlertDialog.Builder dialogs = new AlertDialog.Builder(MainActivity.this);
							dialogs.setTitle("Type of RiskZone");
							dialogs.setItems(R.array.ListOfRiskZone,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											switch (which){
												case 0: startActivity(i1);
														break;
												case 1: startActivity(i2);
														break;
											}

										}
									});
							dialogs.show();		
							break;
							case 1: 
								//startActivity(i3);
							break;
						}

					}
				});
		dialog.show();
	}
	
	/*private boolean checkFileName(){
		File sdCardRoot = Environment.getExternalStorageDirectory();
		File yourDir = new File(sdCardRoot, "/sdcard/EmerMez/riskZone/local/");
		ArrayList<RiskZone> r2 = new ArrayList<RiskZone>();
		r2 = risk.getAllRiskZone(MainActivity.this);
		String listName[]= new String[r2.size()];
		String listFile[];
		int count=0;
		for(RiskZone r : r2){
			listName[count]=r.getId();
			count++;
		}
		count=0;
		for (File f : yourDir.listFiles()) {
		    if (f.isFile()){		        
		        count++;
		        // make something with the name
		    }
		}
		count =0;
		listFile = new String[count];
		
		for (File f : yourDir.listFiles()) {
		    if (f.isFile()){
		    	String name = f.getName();
		    	listFile[count]=name;
		        count++;
		        // make something with the name
		    }
		}
		for(int i =0;i<listFile.length;i++){
			for(int j =0;j<listName.length;i++){
				
			}
		}
		
	}*/
	
	public String getRoadName(double x,double y) throws IOException{		
		
		Geocoder geoCoder = new Geocoder(MainActivity.this);
		List<Address> matches = geoCoder.getFromLocation(x, y, 1);
		Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
		Log.d("Address","bestMatch.getCountryName()");
		if(bestMatch.getThoroughfare()==null)
			addresName="";
		else
			addresName = bestMatch.getThoroughfare();
		return addresName;
	}
	
	public boolean isVertical(ArrayList<LatLng> x){
		double x1[],y1[],checkX1,checkX2,checkY1,checkY2;
		boolean result = false;
		x1 = new double[x.size()];
		y1 = new double[x.size()];
		int count =0;
		for(LatLng d : x){
			x1[count] = d.latitude;
			y1[count] = d.longitude;
			count++;
		}
		checkX1 = x1[0]-0.0010;
		checkX2 = x1[0]+0.0010;
		checkY1 = y1[0]-0.0010;
		checkY2 = y1[0]+0.0010;
		
		
		for(int i=0;i<y1.length;i++){
			if(((y1[i] > (checkY1)) && (y1[i] < (checkY2)))){
				result = true;
			}else{
				result = false;
			}
		}
		return result;
	}
	
	public ArrayList<LatLng> addMorePointInToDirectionPoint(ArrayList<LatLng> x){
		ArrayList<LatLng> newDirectionPoint = new ArrayList<LatLng>();
		double z1,z2,z3,z4,z5,z6;
		LatLng r1,r2,r3,r4,r5,r6;
		for(int i=0;i<x.size();i++){
			if(i==0){
				newDirectionPoint.add(new LatLng(x.get(i).latitude,x.get(i).longitude));
				continue;
			}else{
				z1 = (x.get(i).latitude-x.get(i-1).latitude)/2;
				z2 = (x.get(i).longitude-x.get(i-1).longitude)/2;
				
				z3 =(z1/2);
				z4 =(z2/2);
				
				z5 = (z3/2);
				z6 = (z4/2);
				
				z1 = x.get(i).latitude-z1;
				z2 = x.get(i).longitude-z2;
				
				
				/*r1 = new LatLng(x.get(i-1).latitude+(z3),x.get(i-1).longitude+(z4));
				r2 = new LatLng(z1,z2);
				r3 = new LatLng(x.get(i).latitude-(z3),x.get(i).longitude-(z4));	
				r4 = new LatLng(x.get(i).latitude,x.get(i).longitude);*/
				
				
				r1 = new LatLng(x.get(i-1).latitude+(z5),x.get(i-1).longitude+(z6));
				r2 = new LatLng(x.get(i-1).latitude+(z3),x.get(i-1).longitude+(z4));
				r3 = new LatLng(z1,z2);
				r4 = new LatLng(x.get(i).latitude-(z5),x.get(i).longitude-(z6));
				r5 = new LatLng(x.get(i).latitude-(z3),x.get(i).longitude-(z4));
				r6 = new LatLng(x.get(i).latitude,x.get(i).longitude);
				
				newDirectionPoint.add(r1);				
				newDirectionPoint.add(r2);
				newDirectionPoint.add(r3);
				newDirectionPoint.add(r4);
				newDirectionPoint.add(r5);
				newDirectionPoint.add(r6);
				
				z1 = 0;
				z2 = 0;
				z3 = 0;
				z4 = 0;
				
			}
		}
		return newDirectionPoint;
	}

	private void getOverflowMenu() {

	     try {
	        ViewConfiguration config = ViewConfiguration.get(this);
	        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
	        if(menuKeyField != null) {
	            menuKeyField.setAccessible(true);
	            menuKeyField.setBoolean(config, false);
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	final private OnQueryTextListener queryListener = new OnQueryTextListener() {       
   
	    @Override
	    public boolean onQueryTextSubmit(String query) {            
	        Toast.makeText(MainActivity.this,"Searching for: " + query + "...", Toast.LENGTH_SHORT).show();	        
	        searcAddress(query);
	        return false;
	    }

		@Override
		public boolean onQueryTextChange(String newText) {
			// TODO Auto-generated method stub
			return false;
		}
	};
	
	public void searcAddress(String textSearch){
		LatLng latLng = new LatLng(0,0);
		Geocoder geocoder = new Geocoder(MainActivity.this);
		Address address= null;
        List<Address> addresses = null;
        try {           
            addresses = geocoder.getFromLocationName(textSearch, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for(int i=0;i<addresses.size();i++){        	 
            address = (Address) addresses.get(i);          
            
            latLng = new LatLng(address.getLatitude(), address.getLongitude());           
           
        }
       // mMap.addMarker(new MarkerOptions().position(latLng).title(address.getLocality()).snippet("Your Result").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
				(new LatLng(address.getLatitude(),address.getLongitude())), 15));
        mMap.addMarker(new MarkerOptions()
		.position(latLng)
		.title(address.getLocality())
		.snippet("Your Result")
		
		.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
	}

	/*public void actionBarListener(){
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);	
		actionBar.setDisplayShowTitleEnabled(false);
		
		SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list,
		          android.R.layout.simple_spinner_dropdown_item);
		
		
		ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
			 
            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId) {
            	lanuchItemSelected(itemPosition);
            	
            	return true;
            	            
        }
		};
       	actionBar.setListNavigationCallbacks(mSpinnerAdapter, navigationListener );	
	}*/

	/*private void lanuchItemSelected(int item){
		Intent i;
		switch(item){
		case 3:
			i = new Intent(this,SettingsActivity.class);
			startActivity(i);
			break;
		case 4:
			i = new Intent(this,About.class);
			startActivity(i);
			break;
		}
	}*/

	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case R.id.action_layer:
			openMapOptionDialog();
			try{
			myButton.setVisibility(BIND_ABOVE_CLIENT);
			turnOffLongClickMap();
			
				removePins(x, y);
			}catch (Exception e) {
				// TODO: handle exception
			}			
			break;
		case R.id.action_show_risk_zone:
			Toast.makeText(MainActivity.this, "Risk Zone are shown on the map", 3).show();
			showAllRiskZone();
			/*new AsyncTask<Integer, Long, Boolean>(){

				@Override
				protected Boolean doInBackground(Integer... params) {
					// TODO Auto-generated method stub
					mProgressDialog = new ProgressDialog(MainActivity.this);
					mProgressDialog.setTitle("Load Risk Zones");
					mProgressDialog.setMessage("Please Wait ...");
					mProgressDialog.setMax(params[0]);
					mProgressDialog.setIndeterminate(false);
					publishProgress(0L);
					long start = System.currentTimeMillis();
					long waitTime = params[0]*1000;
					showAllRiskZone();
					try
	                {
	                    while (System.currentTimeMillis() - start < waitTime)
	                    {
	                        Thread.sleep(500);
	                        publishProgress(System.currentTimeMillis() - start);
	                    }
	                }
	                catch (Exception e)
	                {
	                    return false;
	                }

	                return true;
	            }
				 @Override
		            protected void onProgressUpdate(Long... values)
		            {
		                if (values[0] == 0)
		                {
		                    mProgressDialog.show();
		                }
		                else
		                {
		                    mProgressDialog.setProgress((int) (values[0] / 1000));
		                }
		            }
				 @Override
		            protected void onPostExecute(Boolean result)
		            {
					 	mProgressDialog.dismiss();
		                
		            }		 
			
			};*/
			try{
			myButton.setVisibility(BIND_ABOVE_CLIENT);
			turnOffLongClickMap();
			
				removePins(x, y);
			}catch (Exception e) {
				// TODO: handle exception
			}
			break;
		case R.id.action_list_risk_zone:
			openListOfRiskZoneOptions();
			try{
			myButton.setVisibility(BIND_ABOVE_CLIENT);
			turnOffLongClickMap();
			
				removePins(x, y);
			}catch (Exception e) {
				// TODO: handle exception
			}
			break;
		case R.id.action_add_risk_zone:
			addRiskZone();
			enableButton();			
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void addRiskZone(){
		mMap.setOnMapLongClickListener(new OnMapLongClickListener() {
			
			@Override
			public void onMapLongClick(LatLng position) {							
				count+=1;
				Address bestMatch=null;
				if(count==2){
				y1 = position.latitude;
				y2 = position.longitude;						
				try {
					addresName2 = getRoadName(y1,y2);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					addresName2=addresName1;
				}
										
				y = mMap.addMarker( new MarkerOptions().position(position).title(
						"End").snippet(addresName2));						
				
				/*if(addresName1.equals(addresName2)){
					addresName = addresName2;
				}else{
					addresName = addresName1+addresName2;
				}*/				
				Log.d("X1",""+x1);
				Log.d("X2",""+x2);
				Log.d("Y1",""+y1);
				Log.d("Y1",""+y2);
				openInsertDialog();						
				count=0;
				Log.d("Database", "Passing");						
				addresName1 =null;
				addresName2 =null;
				
				}else{
					
					x1 = position.latitude;
					x2 = position.longitude;		
					
					Geocoder geoCoder = new Geocoder(MainActivity.this);
					List<Address> matches;
					try {
						matches = geoCoder.getFromLocation(x1, x2, 1);
						bestMatch = (matches.isEmpty() ? null : matches.get(0));
						addresName1 = bestMatch.getThoroughfare();
						Toast.makeText(MainActivity.this, bestMatch.getThoroughfare().toString(), 3).show();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					x = mMap.addMarker(new MarkerOptions().position(position).title(
							"Start").snippet(addresName1));
					Toast.makeText(MainActivity.this, "Marks another(End) pin", 3).show();
				}
			}
		});
		Toast.makeText(MainActivity.this, "Pin on the map to mark the Risk Zone", 3).show();

	}
	
	public void enableButton(){
		myButton = new Button(this);
		myButton.setText("Cancle");		
		LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		ll.addView(myButton, lp);
		myButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				turnOffLongClickMap();
				myButton.setVisibility(BIND_ABOVE_CLIENT);
				
			}
		});
	}
	
	public void moveToCurrentPosition(){
		Criteria criteria = new Criteria();
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		String provider = locationManager.getBestProvider(criteria,
				false);
		Location location = locationManager
				.getLastKnownLocation(provider);
		double lat = location.getLatitude();
		double lng = location.getLongitude();
		LatLng coordinate = new LatLng(lat, lng);

		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
				(coordinate), 10));
	}

	
	
	

	// Below are method of ActionBar Setting	
	public void actionBar(){
		
		ActionBar actionBar = getActionBar();
		 actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);	
		actionBar.setDisplayShowTitleEnabled(false);
		
		SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list,
		          android.R.layout.simple_spinner_dropdown_item);		
		
		
		ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
			
            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId) {
            	lanuchItemSelected((int)itemId);
            	
            	return true;
            	            
        }
		};
       	actionBar.setListNavigationCallbacks(mSpinnerAdapter, navigationListener );	
	}
	
	private void lanuchItemSelected(int item){
		Intent i;
		switch(item){
		case 3:
			i = new Intent(this,LoginActivity.class);
			startActivity(i);
			break;
		case 4:
			i = new Intent(this,LoginActivity.class);
			startActivity(i);
			break;
		}
	}
	 
	
	
	// Below are method of RiskZone Checking
	// Is in RiskZone
	
	public boolean isInRiskZone(ArrayList<LatLng>[] riskArray,LatLng position){
		 PositionInRiskZone pr = new PositionInRiskZone();
		 return pr.isInPolygon(riskArray,position);
	 }
	
	public ArrayList<LatLng>[] getDirectionPointArray(){
		int count=0;
		
		ArrayList<LatLng> directionPoints[] = new ArrayList[riskArea.size()];
		
		String check = "OK";
		setLink();
		DocumentDirection dd = new DocumentDirection();	
		
		for (RiskZone r : riskArea) {
			
			docs = dd.getDocument("/sdcard/EmerMez/riskZone/local/"
					+ r.getId() + ".xml");	
			
			
			String status = dd.getStatus(docs);
			if(!status.equals(check)){
				continue;
			}else{
			int duration = dd.getDurationValue(docs);
			String distance = dd.getDistanceText(docs);
			String start_address = dd.getStartAddress(docs);
			String copy_right = dd.getCopyRights(docs);
			
			directionPoints[count] = addMorePointInToDirectionPoint(dd.getDirection(docs));
			count++;
			}		
		}
		
		return directionPoints;
	}
	
	
	
	
	
	public PolygonOptions getRectGon() {
		return rectGon;
	}
	
	public void calculateDistance(){		
		float[] x = new float[1];
		Location.distanceBetween(13.687140112679154, 100.53525868803263, 13.683660045847258, 100.53900808095932, x);
		Log.d("Between",""+(int)x[x.length-1]+" metre");
		
	}
	
}

